package com.cloudpivot.receivales.ding.robot.service.baidu;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * 百度 认证 服务
 * 使用rest 调用
 */
@Service
@Slf4j
public class BaiduAuthServiceImpl {

    /**
     * 临时调用使用
     * 后续要从bpm中获取
     */
    public String getToken(String key,String secret) {
        log.info("获取百度 token");
        String reqUrl = String.format("https://aip.baidubce.com/oauth/2.0/token?%s&%s&%s", "grant_type=client_credentials", "client_id=" + key, "client_secret=" + secret);
        log.info("打印百度请求url:{}", reqUrl);
        String token="";
        try {
            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<String> req = new HttpEntity<>(null, headers);
            String ret = restTemplate.postForObject(reqUrl, req, String.class);

            log.info("打印返回:{}", ret);
            JSONObject jsonObject = JSONObject.parseObject(ret);
            token= jsonObject.getString("access_token");
            if (StringUtils.isNotBlank(token)) {
                return token;
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
